package com.yc.vote.servlet;

import com.google.gson.Gson;
import com.yc.vote.biz.BizException;
import com.yc.vote.biz.TpUserBiz;
import com.yc.vote.entity.Result;
import com.yc.vote.entity.TpUser;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    private TpUserBiz biz = new TpUserBiz();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Result result;
        try {
            TpUser user = biz.login(req.getParameter("uname"), req.getParameter("pwd"));
            req.getSession().setAttribute("myinfo", user);
            result = new Result(1, "登录成功",user);
        } catch (BizException e) {
            e.printStackTrace();
            result = new Result(0, e.getMessage(), null);
        }
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().append(new Gson().toJson(result));
    }
}
